// 个人中心页面

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    stats: {
      distance: 0,
      todaySteps: 0,
      weekSteps: 0,
      monthSteps: 0,
      totalSteps: 0
    },
    loading: true,
    refreshing: false
  },

  onLoad: function () {
    // 直接设置为已有用户信息
    this.setData({
      hasUserInfo: true,
      canIUseGetUserProfile: false
    });
    
    // 加载用户信息和统计数据
    this.loadUserProfile();
    this.loadUserStats();
  },

  onShow: function () {
    // 设置tabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 4
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.setData({ refreshing: true });
    
    Promise.all([
      this.loadUserProfile(),
      this.loadUserStats()
    ]).finally(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  // 加载用户个人信息
  loadUserProfile: function () {
    return new Promise((resolve, reject) => {
      // 直接使用静态数据
      const mockUserInfo = {
        id: 1,
        username: 'reduser',
        nickname: '林基路之路体验者',
        avatar: '../../images/avatar.png',
        mobile: '13800138000',
        email: 'red@longmarch.com',
        sex: '男',
        title: '长征路体验者',
        dept: { name: '红色文化体验部' },
        posts: ['体验者'],
        roles: [{ name: '普通用户' }],
        loginDate: new Date().toLocaleString(),
        createTime: '2024-01-01 10:00:00'
      };
      
      this.setData({
        userInfo: mockUserInfo,
        loading: false
      });
      
      // 保存到本地存储
      wx.setStorageSync('userInfo', mockUserInfo);
      resolve();
    });
  },

  // 加载用户统计数据
  loadUserStats: function () {
    return new Promise((resolve, reject) => {
      // 直接使用静态数据
      this.setData({
        stats: {
          distance: 125.6,
          todaySteps: 8856,
          weekSteps: 52341,
          monthSteps: 234567,
          totalSteps: 1234567
        }
      });
      resolve();
    });
  },

  // 获取用户头衔
  getUserTitle: function (roles) {
    if (!roles || roles.length === 0) {
      return '普通用户';
    }
    
    // 根据角色返回相应的头衔
    const roleNames = roles.map(role => role.name);
    if (roleNames.includes('超级管理员')) {
      return '超级管理员';
    } else if (roleNames.includes('管理员')) {
      return '管理员';
    } else if (roleNames.includes('普通角色')) {
      return '注册用户';
    } else {
      return roleNames[0] || '普通用户';
    }
  },



  // 菜单点击事件
  onMenuTap: function (e) {
    const type = e.currentTarget.dataset.type;
    console.log('菜单点击事件触发，类型：', type);
    
    switch (type) {
      case 'steps':
        wx.switchTab({
          url: '/pages/calculate/index'
        });
        break;
      case 'friends':
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
        break;
      case 'ranking':
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
        break;
      case 'products':
        // 尝试打开webview
        wx.navigateTo({
          url: '/pages/webview/index?url=' + encodeURIComponent('http://61.145.250.185:3001/chat/63bd5035-5f26-4f54-943d-6919b9edcb3b'),
          fail: () => {
            // 如果webview失败，回退到复制链接
            wx.setClipboardData({
              data: 'http://61.145.250.185:3001/chat/63bd5035-5f26-4f54-943d-6919b9edcb3b',
              success: () => {
                wx.showModal({
                  title: 'AI助手',
                  content: '链接已复制到剪贴板，请在浏览器中打开使用',
                  showCancel: false
                });
              }
            });
          }
        });
        break;
      case 'route':
        wx.switchTab({
          url: '/pages/example/index'
        });
        break;
      case 'activity':
        wx.navigateTo({
          url: '/pages/feature/activity/index'
        });
        break;
      case 'apply':
        wx.navigateTo({
          url: '/pages/feature/activity/apply'
        });
        break;
      case 'group':
        wx.navigateTo({
          url: '/pages/feature/group/index'
        });
        break;
      case 'calculate':
        wx.switchTab({
          url: '/pages/calculate/index'
        });
        break;
      case 'shop':
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
        break;
      case 'service':
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
        break;
      default:
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
        break;
    }
  },

  // 同步微信步数
  syncWxSteps: function () {
    // 模拟同步成功
    wx.showLoading({
      title: '同步中...'
    });
    
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '同步成功',
        icon: 'success'
      });
      
      // 重新加载步数统计
      this.loadUserStats();
    }, 1500);
  },

  // 编辑个人信息
  editProfile: function () {
    const userInfo = this.data.userInfo;
    
    wx.showModal({
      title: '编辑昵称',
      editable: true,
      placeholderText: userInfo.nickname || '请输入昵称',
      success: (res) => {
        if (res.confirm && res.content) {
          this.updateNickname(res.content);
        }
      }
    });
  },

  // 更新昵称
  updateNickname: function (newNickname) {
    // 直接更新本地数据
    this.setData({
      'userInfo.nickname': newNickname
    });
    
    const userInfo = this.data.userInfo;
    userInfo.nickname = newNickname;
    wx.setStorageSync('userInfo', userInfo);
    
    wx.showToast({
      title: '昵称更新成功',
      icon: 'success'
    });
  },

  // 更换头像
  changeAvatar: function () {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        // 直接使用选择的图片作为头像
        this.setData({
          'userInfo.avatar': tempFilePath
        });
        
        // 更新本地存储
        const userInfo = this.data.userInfo;
        userInfo.avatar = tempFilePath;
        wx.setStorageSync('userInfo', userInfo);
        
        wx.showToast({
          title: '头像更新成功',
          icon: 'success'
        });
      }
    });
  },

  // 清除数据
  logout: function () {
    wx.showModal({
      title: '提示',
      content: '确定要清除所有数据吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.removeStorageSync('userInfo');
          
          // 重新加载默认数据
          this.loadUserProfile();
          this.loadUserStats();
          
          wx.showToast({
            title: '数据已重置',
            icon: 'success'
          });
        }
      }
    });
  },

  // 分享功能
  onShareAppMessage: function () {
    return {
      title: '重走长征路，用脚步丈量历史',
      path: '/pages/index/index',
      imageUrl: '../../images/avatar.png'
    };
  },

  goToRedProduct() {
    wx.navigateTo({
      url: '/pages/webview/index?url=' + encodeURIComponent('http://61.145.250.185:3001/chat/63bd5035-5f26-4f54-943d-6919b9edcb3b')
    });
  }
}); 